import 'package:flutter/material.dart';
import 'package:flutter_mwm/base/base.dart';
import 'package:flutter_mwm/beans/bean.dart';
import 'package:flutter_mwm/impl/http.dart';
import 'package:flutter_mwm/settings/settings.dart';
import 'package:flutter_mwm/ui/main.dart';
import 'package:flutter_mwm/widget/button.dart';
import 'package:flutter_mwm/widget/edit.dart';

import '../impl/impl.dart';
import '../ui/register.dart';
import '../util/util.dart';
import '../widget/widget.dart';

class LoginHome extends BaseWidget<LoginHome> {
  @override
  State<StatefulWidget> createState() {
    return _StateLogin();
  }
}

class _StateLogin extends StateBase<LoginHome> implements HttpCallbackImpl {
  TextEditingController _accountController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _getShared();
  }

  Future<Null> _getShared() async {
    String account = await PreferUtil.get(StrImpl.KEY_ACCOUNT);
    if (!TextUtils.isEmpty(account)) {
      _accountController.text = account;
    }
    String password = await PreferUtil.get(StrImpl.KEY_PASSWORD);
    if (!TextUtils.isEmpty(password)) {
      _passwordController.text = password;
    }
  }

  @override
  Widget build(BuildContext context) {
    return PhotoWallpaper(
      context,
      fullScreen: true,
      child: _loginForm(),
    );
  }

  Widget _loginForm() {
    return ListView(
      shrinkWrap: true,
      children: <Widget>[
        _inputForm(),
        _linkButton(),
        _loginButton(),
      ],
    );
  }

  Widget _inputForm() {
    return Container(
      margin: EdgeInsets.all(10.0),
      padding: EdgeInsets.symmetric(horizontal: 8.0),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8.0)),
          color: Colors.white,
          border: Border.all(color: Color(0xFF003355), width: 3.0)),
      child: Column(children: <Widget>[
        EditText(
          showClearIcon: true,
            labelText: '用户账号(仅限数字和字母)',
            keyboardType: TextInputType.emailAddress,
            controller: _accountController,),
        _driverLine(),
        EditText(
            showClearIcon: true,
            keyboardType: TextInputType.emailAddress,
            labelText: '用户密码',
            obscureText: true,
            controller: _passwordController),
      ]),
    );
  }

  Widget _driverLine() {
    return Line(color: Color(0xFF00cccc));
  }

  Widget _linkButton() {
    return Container(
        margin: EdgeInsets.all(10.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            _textButton("程序设置", _link2Settings),
            _textButton("立即注册", _link2RegisterForResult)
          ],
        ));
  }

  Widget _textButton(String text, VoidCallback callback) {
    return ButtonText(
      text,
      textSize: 18.0,
      textColor: Color(0xFF0099CC),
      highlightTextColor: Color(0xFF0066CC),
      onPressed: callback,
    );
  }

  Widget _loginButton() {
    return Row(
      children: <Widget>[
        ExpandedButton("登  录",
            radius: 8.0,
            background: Color(0xFF3d6488),
            highlightBackground: Color(0xFF3d7999),
            margin: EdgeInsets.only(top: 10.0, left: 8.0, right: 8.0),
            padding: EdgeInsets.all(10.0),
            highlightTextColor: Colors.white,
            textColor: Color(0xFF0099CC),
            textSize: 18.0,
            onPressed: _login)
      ],
    );
  }

  Future<Null> _login() async {
    String account = _accountController.text;
    if (TextUtils.isEmpty(account)) {
      showToast('用户名不能为空！');
      return;
    }
    String password = _passwordController.text;
    if (TextUtils.isEmpty(password)) {
      showToast('密码不能为空！');
      return;
    }
    Map<String, String> map = await PlatformKit.device();
    AccountBean accountBean = AccountBean(
        username: account,
        password: password,
        serial: map['deviceSerial'],
        device: map['deviceModel']);
    Map<String, String> bodyParams = {
      'beanJson': GsonUtil.bean2Json(accountBean)
    };
    var http = HttpKit.getInstance(context: context);
    http.setTag(accountBean).callback(this);
    http.execute(method: 'login', paramBody: bodyParams);
  }

  _link2Settings() {
    Navigator.push(context, MaterialPageRoute(builder: (_) => SettingsHome()));
  }

  _link2RegisterForResult() {
    Navigator.push(context, MaterialPageRoute(builder: (_) => RegisterHome()))
        .then((value) {
      if (!TextUtils.isEmpty(value)) {
        _accountController.text = value;
        _passwordController.text = '';
      }
    });
  }

  @override
  void onResult(int what, Object tag, String result) {
    try {
      Log.out(result);
      ReturnAccountBean resultBean = ReturnAccountBean.json2Bean(result);
      if (null == resultBean) {
        showPromptDialog("数据格式错误或未返回数据！");
        return;
      }
      var code = resultBean.code;
      var message = resultBean.message;
      if (!TextUtils.equals("1", code)) {
        showPromptDialog(message);
        return;
      }
      AccountBean accountBean = tag;
      String username = accountBean.username;
      String password = accountBean.password;
      accountBean.signature=resultBean.obj.signature;
      PreferUtil.set(StrImpl.KEY_ACCOUNT, username);
      PreferUtil.set(StrImpl.KEY_PASSWORD, password).then((_) {
        _start2Main(accountBean);
      });
    } catch (error) {
      onError(what, tag, error.toString());
    }
  }

  void _start2Main(AccountBean accountBean) {
    Navigator.pushAndRemoveUntil(
        context,
        MaterialPageRoute(builder: (_) => MainHome(accountBean: accountBean)),
        (route) => route == null);
  }

  @override
  void onError(int what, Object tag, String error) {
    showErrorPromptDialog("登录失败", error);
  }
}
